package com.lbn.monitor.widget.calendar2;

import android.app.DatePickerDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.PopupWindow;

import com.lbn.monitor.R;
import com.lbn.monitor.base.AppBaseActivity;

import java.util.Calendar;

public class CalendarPopupWindow implements DatePicker.OnDateChangedListener, View.OnClickListener {

    private PopupWindow mPopupWindow;

    private DatePicker datePicker;

    private String date;

    private Button button;

    private OnChangedDate onChangedDate;

    public void createPopup(Context context) {
        Calendar calendar = Calendar.getInstance();
        View popupView = LayoutInflater.from(context).inflate(R.layout.activity_calendar, null);
        button = (Button) popupView.findViewById(R.id.button);
        button.setOnClickListener(this);
        datePicker = (DatePicker) popupView.findViewById(R.id.date_picker);
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH);
        int day = calendar.get(Calendar.DAY_OF_MONTH);
        datePicker.init(year, month, day, this);
        month = month + 1;
        date = year+"-"+ (month<10?"0"+month:month) + "-" + (day<10?"0"+day:day);
        mPopupWindow = new PopupWindow(popupView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
        mPopupWindow.setTouchable(true);
        mPopupWindow.setOutsideTouchable(true);
        mPopupWindow.setBackgroundDrawable(new BitmapDrawable(context.getResources(), (Bitmap) null));

        popupView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPopupWindow.dismiss();
            }
        });
    }


    public void show(View v) {
        mPopupWindow.showAtLocation(v, Gravity.CENTER, 0, 0);
    }


    public void dismiss() {
        mPopupWindow.dismiss();
    }


    @Override
    public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        monthOfYear = monthOfYear+1;
        date = year + "-" + (monthOfYear<10?"0"+monthOfYear:monthOfYear) + "-" + (dayOfMonth<10?"0"+dayOfMonth:dayOfMonth);
    }

    @Override
    public void onClick(View v) {
        if (onChangedDate != null) {
            onChangedDate.onChangedDate(date);
        }
        dismiss();
    }

    public void setOnChangedDate(OnChangedDate onChangedDate) {
        this.onChangedDate = onChangedDate;
    }

    public interface OnChangedDate {
        void onChangedDate(String date);
    }
}
